import React from 'react';
import qs from 'qs';
import {Row,Modal,message,Upload,Col} from 'antd';
import * as Constant from '../../../common/const';
import LimitMACModalForm from "./LimitMACModal";
import {AuthA,AuthButton} from '../../auth/OperationAuth';
import TablePage from "../../TablePage";

import {getPageParams,downloadExcel,getButtonCol} from '../../../common/utils';
require('../../systemManager/customer.css');

const defaultQuery = {page:Constant.DEFAULT_PAGE,size:Constant.DEFAULT_PAGE_SIZE};
const confirm = Modal.confirm;
const success = Modal.success;

class LimitMACTable extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            dataSource:[],
            pagination:{},
            loading:true,
            visible:false,
            mac:undefined,
            title:undefined,
        };
    }

    componentDidMount() {
        this.fetchData();
    }

    componentWillUnmount() {
        this.setState = () => {
            return;
        };
    }


    fetchData = (params = defaultQuery) => {
        this.setState({
            loading:true
        });
        this.props.page(qs.stringify(params)).then(res => {
            if(res && Constant.REQUEST_SUCCESS == res.code){
                let data = res.data;
                this.setState({
                    dataSource:data.content,
                    pagination:{...this.state.pagination,total:data.totalSize,current:data.page + 1,pageSize:params.size},
                    loading:false,
                });
            }
        });
    }

    add = () => {
        this.setState({
            visible:true,
            mac:undefined,
            title:'添加' + this.props.title
        })
    }

    cancel = (flag = false) => {
        if(typeof flag == 'object'){
            flag = false;
        }
        this.setState({
            visible:false
        });
        flag && this.fetchData(getPageParams(this.state.pagination));
    }
    /* 编辑 */
    edit = (id) => {
        this.props.find(id).then(res => {
            if( res && Constant.REQUEST_SUCCESS == res.code){
                this.setState({
                    visible: true,
                    mac:res.data,
                    title:'修改' + this.props.title
                });
            }
        });
    }
    /* 删除 */
    delete = (id) =>{
        confirm({
            title: '删除提示',
            content: '确认删除该条信息',
            maskClosable: true,
            okText: '确定',
            okType:'primary',
            cancelText: '取消',
            onOk:() => {
                this.props.delete(id).then(res => {
                    if( res && Constant.REQUEST_SUCCESS == res.code){
                        this.fetchData(getPageParams(this.state.pagination,true));
                        message.success(Constant.DELETE_SUCCESS_TIP,Constant.AUTO_DISAPPEAR_TIME);
                    }
                })
            }
        });
    }

    /* 翻页 */
    handleTableChange = (pagination) => {
        const _this = this;
        const pager = { ..._this.state.pagination };
        pager.current = pagination.current;
        pager.pageSize = pagination.pageSize;
        _this.setState({
            pagination: pager,
            loading:true
        });
        _this.fetchData(getPageParams(pagination));
    }

    //导入成功方法
    importSuccessFunc = (file) => {
        if (file.code == Constant.REQUEST_SUCCESS) {
            if(file.data&&file.data.length>0){
                let rowItem = file.data.map((item)=>{
                    return <Row className='info-row'>{item.mac}</Row>
                })
                success({
                    title: '导入成功，请检查重复MAC地址',
                    content: rowItem,
                    maskClosable: true,
                    centered: true,
                    // width: 300,
                    style:{
                        textAlign: 'center'
                    },
                })
            }else{
                message.success('导入成功', Constant.AUTO_DISAPPEAR_TIME);
            }
            this.fetchData();
        } else {
            message.error(file.msg, Constant.ERROR_DISAPPEAR_TIME);
        }
    }

    //批量导出方法
    outPutFunc = () => {
        const { title } = this.props;
        this.props.export().then(res => {
            const {data,headers} = res;
            var blob = new Blob([data], { type: 'application/vnd.ms-excel;charset=utf-8' }); //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
            const filename = title+'.xlsx';
            downloadExcel(blob, filename, data);
        })
    }

    render() {
        const columns = [
            {
                title:"主键",
                dataIndex:"id",
                width:'33.33%',
                align:'center',
            },
            {
                title:"MAC地址",
                dataIndex:"mac",
                width:'33.33%',
                align:'center'
            },
            {
                title:"操作",
                width:'33.33%',
                align:'center',
                render:(text, record) =>
                    (
                        <span>
                             <AuthA onClick={this.edit.bind(this,record.id)} className={'operation-primary'} permission={'controlMac:save'}>编辑</AuthA>
                             <AuthA onClick={this.delete.bind(this,record.id,record.name)} className={'operation-danger'} permission={'controlMac:delete'}>删除</AuthA>
                         </span>
                    )
            }
        ];
        //批量导入配置文件
        const uploaderProps = {
            action: this.props.importUrl,
            headers: {
                authorization: 'authorization-text',
            },
            fileList: [],
            onSuccess: this.importSuccessFunc //文件请求完成返回方法
        };

        return (
            <div>
                <Row className="button-margin">
                    <Col {...getButtonCol('controlMac:save')} className="button-margin">
                        <AuthButton size={'large'} onClick={this.add} className={'ant-btn-large'} permission={'controlMac:save'}>
                            添加信息
                        </AuthButton>
                    </Col>
                    <Col {...getButtonCol('controlMac:save')} className="button-margin">
                        <Upload {...uploaderProps}>
                            <AuthButton size='large' permission={'controlMac:save'}>
                                批量导入
                            </AuthButton>
                        </Upload>
                    </Col>
                    <Col {...getButtonCol('controlMac:all')} className="button-margin">
                        <AuthButton size={'large'} onClick={this.outPutFunc} className={'ant-btn-large'} permission={'controlMac:all'}>
                            批量导出
                        </AuthButton>
                    </Col>
                </Row>
                <Row>
                    <TablePage
                        dataSource={this.state.dataSource}
                        columns={columns}
                        rowKey={record => record.id}
                        pagination={this.state.pagination}
                        loading={this.state.loading}
                        onChange={this.handleTableChange}
                    />
                </Row>
                <Row>
                    <Modal
                        title={this.state.title}
                        visible={this.state.visible}
                        footer={null}
                        onCancel={this.cancel}
                        maskClosable={false}
                        destroyOnClose={true}
                        centered={true}
                    >
                        <LimitMACModalForm
                            cancel={this.cancel}
                            save={this.props.save}
                            update={this.props.update}
                            mac={this.state.mac}
                            validator = {this.props.validator}
                        />
                    </Modal>
                </Row>
                <style>{`
                    .ant-confirm-success .ant-confirm-body > .anticon {
                        margin-left: -65%;
                    }
                    .ant-confirm-success .ant-confirm-body .ant-confirm-title {
                        margin-left: 6%; 
                    }
                `}</style>
            </div>
        );
    }

}

export default LimitMACTable;